package aip.ui.attachment.util;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

/**
 * 缩略图帮助类
 * <p>
 * 负责人/principal: Daniel<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:
 * @author RUN
 * @version $Id: codetemplates.xml 2007 2009-05-08 08:36:14Z shiw $
 */
public class ThumbnailUtils
{
    public static BufferedImage resize(BufferedImage source, int targetW,
            int targetH)
    {
        // 在targetW，targetH范围内等比缩放
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        double s = Math.min(sx, sy);
        targetW = sx > s ? (int) (s * source.getWidth()) : targetW;
        targetH = sy > s ? (int) (s * source.getHeight()) : targetH;

        int type = source.getType();
        BufferedImage target = null;
        if (type == BufferedImage.TYPE_CUSTOM)
        {
            // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
                    targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        }
        else
        {
            target = new BufferedImage(targetW, targetH, type);
        }
        Graphics2D g = target.createGraphics();
        // 选择偏重输出质量的合适呈现算法(慢)
        // g.setRenderingHint(RenderingHints.KEY_RENDERING,
        // RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(s, s));
        g.dispose();
        return target;
    }
}
